package com.glodon.paas.document.dao.mysql;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

import com.glodon.paas.document.dao.RevisionDao;
import com.glodon.paas.document.dao.domain.RevisionEntity;
import com.glodon.paas.document.dao.mapper.RevisionEntityMapper;

public class RevisionDaoMysqlImpl implements RevisionDao {

    @Autowired
    RevisionEntityMapper revisionEntityMapper;

    @Override
    public String insert(RevisionEntity entity) {
        revisionEntityMapper.insertSelective(entity);
        return entity.getId();
    }

    @Override
    public RevisionEntity get(String id) {
        return revisionEntityMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delete(String id) {
        return revisionEntityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<RevisionEntity> getRevisionsByFile(String fileId) {
        return revisionEntityMapper.getRevisionsByFileId(fileId);
    }

    @Override
    public RevisionEntity getLatestUnavailableRevision(String fileId) {
        List<RevisionEntity> list = revisionEntityMapper.getLatestUnavailableRevision(fileId);
        if (list.size() > 1) {
            //
            // logger.warn("duplicate RevisionEntity. fileId="+fileId);
            return list.get(0);
        }

        if (list.size() == 1) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public RevisionEntity getRevision(String fileId, int revisionNum) {
        return revisionEntityMapper.selectRevisionByRevisionNum(fileId, revisionNum);
    }

    @Override
    public void updateRevision(RevisionEntity revision) {
        revisionEntityMapper.updateByPrimaryKeySelective(revision);
    }

    @Override
    public void updateDataBagId(String revisionId, String dataBagId) {
        revisionEntityMapper.updateRevisionTaskId(revisionId, dataBagId);
    }

    @Override
    public RevisionEntity getLatestAvailableRevision(String fileId) {
        return revisionEntityMapper.getLatestAvailableRevision(fileId);
    }

    @Override
    public void deleteByFile(String fileId) {
        revisionEntityMapper.deleteByFile(fileId);
    }

    @Override
    public RevisionEntity getRevisionByDatabag(String databagId) {
        return revisionEntityMapper.getRevisionByDatabag(databagId);
    }
}
